package top.codedance.iotp.registy.net.handle;

import cd.io.netty.channel.ChannelHandlerContext;
import cd.io.netty.channel.SimpleChannelInboundHandler;
import cd.io.netty.channel.socket.SocketChannel;
import cd.io.netty.handler.codec.http.FullHttpRequest;

public class HttpChannelHandler extends SimpleChannelInboundHandler<Object> {

    private SocketChannel channel;
    private HttpMsgHandlerImpl handler;

    public HttpChannelHandler(SocketChannel channel){
        this.channel = channel;
    }

    protected void messageReceived(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        if(msg instanceof FullHttpRequest) {
            handler = new HttpMsgHandlerImpl();
        }else{
            channelHandlerContext.close();
            channel.close();
        }
        handler.channelRead(channelHandlerContext, msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        if(handler != null) {
            handler.handlerRemoved(ctx);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if(handler != null) {
            handler.exceptionCaught(ctx, cause);
        }
    }
}
